package com.jkkc.lib.base.util

import android.serialport.SerialPort
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.SimpleTask
import com.blankj.utilcode.util.ToastUtils

/**
 * Author:LiXian
 * <p>
 * Desc:打印工具类
 * Version:1.0
 * date 2023/2/8 11:33
 */
object PrintUtils {

    private var mSerialPort: SerialPort? = null

    /**
     * 初始化串口
     *
     * @param devicePath 设备串口路径
     * @param baudrate 波特率
     */
    @JvmStatic
    fun init(devicePath: String, baudrate: Int) {
        if (mSerialPort == null) {
            try {
                mSerialPort = SerialPort.newBuilder(devicePath, baudrate).build()
                ToastUtils.showShort("打印机初始化完成")
            } catch (e: Exception) {
                ToastUtils.showShort(e.message)
            }
        }
    }

    fun isInitPrinter(): Boolean = (mSerialPort != null)

    /**
     * 关闭串口
     */
    @JvmStatic
    fun close() {
        mSerialPort?.tryClose()
        mSerialPort = null
    }

    @JvmStatic
    @JvmOverloads
    fun print(contents: List<String>, callback: ((Boolean) -> Unit)? = null) {
        if (mSerialPort == null) {
            ToastUtils.showShort("打印机初始化失败")
            callback?.invoke(false)
            return
        }
        //子线程里面打印
        val mTask: ThreadUtils.Task<Boolean> = object : SimpleTask<Boolean>() {
            @Throws(Throwable::class)
            override fun doInBackground(): Boolean {
                val writes = mutableListOf<ByteArray>()
                contents.forEach {
                    writes.add(it.toByteArray(charset("GB2312")))
                }
                for (bs in writes) {
                    mSerialPort?.outputStream?.write(bs)
                    //留给热敏打印机打印时间，缓存有限，不能一直发数据给他
                    Thread.sleep(1500)
                }
                return true
            }

            override fun onSuccess(result: Boolean) {
                callback?.invoke(result)
                cancel()
            }

            override fun onFail(t: Throwable?) {
                super.onFail(t)
                callback?.invoke(false)
                cancel()
            }
        }
        ThreadUtils.executeBySingle(mTask)
    }
}